import { useState, useEffect } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import { useKeyPress } from 'ahooks';
import './App.css'

function getRandomInt(a, b) {  
  // 确保a小于b，如果不是则交换它们  
  if (a > b) {  
      [a, b] = [b, a];  
  }  

  // 生成一个介于a和b之间的随机整数（包括a和b）  
  return Math.floor(Math.random() * (b - a + 1)) + a;  
} 
const blockList = [
  [
    [1,1],
    [1,1]
  ],
  [
    [0,1,0],
    [1,1,1]
  ],
  [
    [1,1,1,1]
  ],
  [
    [1,0,0],
    [1,1,1]
  ],
  [
    [0,0,1],
    [1,1,1]
  ]
]

const displayStart = new Array(20).fill(1).map(()=>{
  const rel = new Array(10).fill(0)
  return [...rel]
})

function App() {
  const [nowItem, setNowItem] = useState([]) 
  const [running , setRun] = useState(false)
  console.log(displayStart)
  const [blocks, setBlock] = useState(displayStart); // 显示界面
  const [nowY, setY] = useState(0);
  const [nowX, setX] = useState(0);
  const [ground, setGround] = useState(displayStart) // 已经落下的方块 

  // 创建下一个方块
  const createNextBlock = () => {
    const index = getRandomInt(0, blockList.length-1);
    console.warn('啥方块：',blockList[index])
    setNowItem(blockList[index]);
  }

  const autoDown=() =>{
    setY(v => v+1)
  }

  useKeyPress('uparrow', () => {
    // => >> >>> >>>> >>>>> // 
  })
  useEffect(() => {
    const interval =setInterval(() => {
      // 什么时候生成下一个方块呢？
      if(running) {
        console.error('noyY',nowY)
        autoDown(v => v+1)
        console.error('noyY',nowY)
        // 方块下落
        setBlock(v => {
          return ground.map((a,i)=> {
            return a.map((b,j) => {
              if (i >= nowY&& j>= nowX) {
                if (i< nowY+nowItem.length  && j<nowX+nowItem[0]?.length ) {
                  // console.log('满足条件',i,j,i-nowY,j-nowX,nowItem);
                  return nowItem[i-nowY][j-nowX];
                }
                return ground[i][j]
              }
              return ground[i][j]
            })
          })
        })
        // 判断是否是触底 
        const bottomBlocks = nowItem[nowItem.length-1];
        // 
        if(nowY+nowItem.length == blocks.length) {
          console.log('触底', blocks)
          console.log('底',blocks[blocks.length-1])
          setGround(blocks);
          createNextBlock();
          setY(0)
        }
        console.log(blocks)
      }
    },1000);
    return () => {
      clearInterval(interval);
    }
  })

  useKeyPress('enter', () => {
    if (!running) {
      // setY(v => v+1)
      setRun(true);
      // 生成方块 
      createNextBlock()
    }
  })
  return (
    <>
      <div className='grid grid-cols-10 w-64'>
        {blocks.map((v, i) => {
          // console.log('???',v);
          return v?.map((a,j)=>{
            return <div className={`border border-yellow-600 ${a?'bg-red-600':''}`} key={i+','+j}>&nbsp;</div>
          })
        })}
      </div>
      <p> 按回车开始游戏 </p>
    </>
  )
}

export default App
